package com.imooc.miaosha.web;

import com.imooc.miaosha.entity.User;
import com.imooc.miaosha.redis.RedisConfig;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.redis.UserKey;
import com.imooc.miaosha.result.Result;
import com.imooc.miaosha.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Controller
 * 1.rest api json输出 2.页面
 *
 * @author simple
 */
@Slf4j
@Controller
public class DemoController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisConfig redisConfig;

    @RequestMapping("")
    @ResponseBody
    String home() {
        return redisConfig.toString();
    }

    @RequestMapping("/thymeleaf")
    public String thymeleaf(Model model) {
        model.addAttribute("name", "Joshua");
        return "hello";
    }

    @RequestMapping("db/get")
    @ResponseBody
    public Result<User> dbGet() {
        log.error("this is db/get");
        log.error(redisConfig.toString());
        return Result.success(userService.getById(1));
    }

    @RequestMapping("db/tx")
    @ResponseBody
    public Result<User> dbTx() {
        log.error("this is db/tx");
        boolean b = userService.tx();
        return Result.success(userService.getById(1));
    }

    @RequestMapping("redis/getUser")
    @ResponseBody
    public Result<User> redisGetUser() {
        User u1 = userService.getById(1);
        redisService.set(UserKey.getById, "key1", u1);
        log.error("u1[{}]", u1);
        User u2 = redisService.get(UserKey.getById, "key1", User.class);
        log.error("u2[{}]", u2);
        log.error("this is redis/get");
        return Result.success(userService.getById(1));
    }

    @RequestMapping("redis/getLong")
    @ResponseBody
    public Result<Long> redisGetLong() {
        Long l1 = redisService.get("key1", Long.class);
        log.error("this is redis/getLong");
        User user = userService.getById(1);
        boolean b = redisService.set("key2", user);
        log.error("boolean" + b);
        log.error("User" + redisService.get("key2", User.class).toString());
        return Result.success(l1);
    }
}
